package com.zyh.server.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyh.server.config.Constant;
import com.zyh.server.entity.MiaoshaMsg;
import com.zyh.server.entity.User;
import com.zyh.server.rabbitmq.MQSender;
import com.zyh.server.service.MiaoshaService;
import com.zyh.server.service.OrderService;
import com.zyh.server.utils.R;
import com.zyh.server.utils.RedisUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @Author: zyh
 * @Date: 2024-11-19-8:45
 * @Description
 */
@Tag(name = "秒杀模块")
@Slf4j
@RestController //@Controller + @ResponseBody后端传递json数据
@RequestMapping("/miaosha")
@CrossOrigin(origins = "*") //允许跨域请求
public class MiaoshaController {
	//秒杀：谁买什么商品，下单，减库存
	// 问题1：谁?  @RequestHeader("token") String token 从redis中获取User
	// 问题2：判断用户是否重复秒杀，要求每个用户只能买1个商品
	// 问题3：购买之前需要判断秒杀库存？
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private OrderService orderService;
	@Autowired
	private MiaoshaService miaoshaService;
	@Autowired
	private MQSender mqSender;

	@Operation(summary = "秒杀方法")
	@Parameters({
			@Parameter(name = "token", description = "用户token值", in = ParameterIn.HEADER),
			@Parameter(name = "miaoshaGoodsId", description = "秒杀商品ID", in = ParameterIn.PATH)
	})
	@GetMapping("/exec/{miaoshaGoodsId}")
	public R exec(@RequestHeader("token") String token,
	              @PathVariable("miaoshaGoodsId") Integer miaoshaGoodsId) {
		//第1步：根据token值获取user对象
		Object userObj = redisUtil.getObj(Constant.REDIS_TOKEN_PREFIX + token);
		User user = new ObjectMapper().convertValue(userObj, User.class);
		log.info("秒杀方法---->user信息:{}", user);
		//第2步：判断此用户是否已经秒杀过此商品
		String orderId = orderService.checkOrder(user.getId(), miaoshaGoodsId);
		log.info("秒杀方法---->orderId:{}", orderId);
		if (Objects.nonNull(orderId)) {
			return R.fail().setMsg("秒杀失败，您已经秒杀过此商品!");
		}
		// 创建消息（异步处理数据）
		MiaoshaMsg miaoshaMsg = new MiaoshaMsg();
		miaoshaMsg.setUser(user);
		miaoshaMsg.setMiaoshaGoodsId(miaoshaGoodsId);
		mqSender.send(miaoshaMsg);
		return R.ok().setMsg("秒杀任务正在处理中!");
	}


	@Operation(summary = "获取秒杀结果")
	@Parameters({
			@Parameter(name = "token", description = "用户token值", in = ParameterIn.HEADER),
			@Parameter(name = "miaoshaGoodsId", description = "秒杀商品ID", in = ParameterIn.PATH)
	})
	@GetMapping("/result/{miaoshaGoodsId}")
	public R result(@RequestHeader("token") String token,
	                @PathVariable("miaoshaGoodsId") Integer miaoshaGoodsId) {
		log.info("token:{}",token);
		//第1步：根据token值获取user对象
		Object userObj = redisUtil.getObj(Constant.REDIS_TOKEN_PREFIX + token);
		User user = new ObjectMapper().convertValue(userObj, User.class);
		log.info("user信息:{}", user);
		return miaoshaService.getMiaoshaResult(user.getId(), miaoshaGoodsId);
	}
}
